from encryption import Encryption
from sys_config_reader import SysConfigReader
import logging

class SysServerConfig(object):


    def __init__(self,sys_config:SysConfigReader) -> None:
        self.sys_config = sys_config

        self.server_config = sys_config.server
        self.path=self.server_config["path"]
        self.off=self.server_config["off"]
        self.model=self.server_config["model"]
        self.entryption_key=self.server_config["entryption_key"]
        pass

    def load(self):
        """加载服务器配置"""
        if(self.off):
            return self.sys_config.server_list()
        else:
            # 加密配置打开
            if(self.entryption_key):
                # 解密服务器配置
                return self.sys_config.server_decrypt()
            else:
                # 首次启动,生成服务器配置加密文件
                self.gen_encrypt()
                return self.sys_config.server_decrypt()
            
    def gen_encrypt(self):
        """生成加密的服务器配置"""
        
        key = Encryption.gen_key();
        self.server_config["entryption_key"] = key
        self.sys_config.server = self.server_config
        self.sys_config.write_sys_file()

        try:
            self.sys_config.server_encrypt_write()
        except:
            logging.error("server configuration encryption failed,reset [entryption_key]")
            self.server_config["entryption_key"]=""
            self.sys_config.server = self.server_config
            self.sys_config.write_sys_file()

    